from django.shortcuts import render

# Create your views here.
from django.http import JsonResponse
from django.views import View
from haystack.views import SearchView

from apps.goods.models import GoodsCategory, SKU
from utils.goods import *
from django.core.paginator import Paginator


class ListView(View):
    def get(self, request, category_id):
        # 1、获取前端数据
        page = request.GET.get('page')
        page_size = request.GET.get('page_size')
        ordering = request.GET.get('ordering')
        # 2、校验数据
        if not all([category_id, page, page_size, ordering]):
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        # 3、查询数据
        try:
            category = GoodsCategory.objects.get(id=category_id)
        except GoodsCategory.DoesNotExist as e:
            return JsonResponse({'code': 400, 'errmsg': '获取mysql数据出错'})
        # 查询面包屑导航(函数在下面写着)
        breadcrumb = get_breadcrumb(category)
        try:
            # skus = category.sku_set.filter(is_launched=True).order_by(ordering)
            skus = SKU.objects.filter(category=category,
                                      is_launched=True).order_by(ordering)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '获取mysql数据出错'})

        p = Paginator(skus, page_size)
        page_list = p.page(page).object_list
        skus_list = [{
            'id': sku.id,
            'name': sku.name,
            'caption': sku.caption,
            # 'url': sku.,
            'default_image_url': sku.default_image.url,
            'price': sku.price,
            'comments': sku.comments,
        } for sku in page_list]
        count = p.num_pages
        # 4、返回Json数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'count': count,
                             'list': skus_list, 'breadcrumb': breadcrumb})


class HotView(View):
    def get(self, request, category_id):
        # 1、前端数据
        # 2、检验数据
        if not category_id:
            return JsonResponse({'code': 400, 'errmsg': '参数缺失'})
        skus = SKU.objects.filter(category_id=category_id,
                                  is_launched=True).order_by('-sales')[:2]
        hot_list = [{
            'id': sku.id,
            'name': sku.name,
            'caption': sku.caption,
            'price': sku.price,
            'stock': sku.stock,
            'sales': sku.sales,
            'comments': sku.comments,
            # 'url': ,
            'default_image_url': sku.default_image.url,

        } for sku in skus]
        # 3、返回Json数据
        return JsonResponse({'code': 0, 'errmsg': 'ok', 'hot_skus': hot_list})


class SKUSearchView(SearchView):

    def create_response(self):
        context = self.get_context()
        search_res = context['page'].object_list
        sku_list = [{
            'id': sku.object.id,
            'name': sku.object.name,
            'price': sku.object.price,
            'default_image_url': sku.object.default_image.url,
            'searchkey': context.get('query'),
            'page_size': context['page'].paginator.num_pages,
            'count': context['page'].paginator.count
        } for sku in search_res]
        return JsonResponse(sku_list, safe=False)


class DetailView(View):
    """商品详情页"""

    def get(self, request, sku_id):
        """提供商品详情页"""
        # 获取当前sku的信息
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})
        # 查询商品频道分类
        categories = get_categories()
        # 查询面包屑导航
        breadcrumb = get_breadcrumb(sku.category)
        # 查询SKU规格信息
        goods_specs = get_goods_specs(sku)

        # 渲染页面
        context = {
            'categories': categories,
            'breadcrumb': breadcrumb,
            'sku': sku,
            'specs': goods_specs,
        }
        return render(request, 'detail.html', context)


class DetailVisitView(View):
    """详情页分类商品访问量"""

    def post(self, request, category_id):
        try:
            # 1.获取当前商品
            category = GoodsCategory.objects.get(id=category_id)
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '缺少必传参数'})

        # 2.查询日期数据
        from datetime import date
        # 获取当天日期
        today_date = date.today()
        from apps.goods.models import GoodsVisitCount
        try:
            # 3.如果有当天商品分类的数据  就累加数量
            count_data = category.goodsvisitcount_set.get(date=today_date)
        except:
            # 4. 没有, 就新建之后在增加
            count_data = GoodsVisitCount()
        try:
            count_data.count += 1
            count_data.category = category
            count_data.save()
        except Exception as e:
            return JsonResponse({'code': 400, 'errmsg': '新增失败'})

        return JsonResponse({'code': 0, 'errmsg': 'OK'})
